package com.gsbelarus.gedemin.salary.receiver;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.gsbelarus.gedemin.lib.sync.protocol.SyncServiceModel;
import com.gsbelarus.gedemin.lib.sync.protocol.entity.SyncServiceTask;
import com.gsbelarus.gedemin.salary.entity.SyncRequestType;
import com.gsbelarus.gedemin.salary.service.SyncService;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                Log.i(this.getClass().getSimpleName(), "Send error: " + extras.toString());

            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                Log.i(this.getClass().getSimpleName(), "Deleted messages on server: " + extras.toString());

            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                Log.i(this.getClass().getSimpleName(), "Received: " + extras.toString());
                //String msg = extras.getString("message");

                context.startService(SyncServiceModel.getIntentWithTask(new Intent(context, SyncService.class),
                        SyncServiceTask.TypeOfTask.SERIES_SYNC,
                        new SyncRequestType(SyncRequestType.TypeOfRequest.MSG_REQUEST),
                        true));

            }
        }
    }
}
